/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.osdtsystem.utils;

import gnu.trove.TIntHashSet;
import gnu.trove.TIntIterator;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;

/**
 *
 * @author mwh
 */
public class TroveIntHashSet extends AbstractSet<Integer> {

    TIntHashSet set;

    public TroveIntHashSet() {
        set = new TIntHashSet();
    }

    public TroveIntHashSet(int capacity) {
        set = new TIntHashSet(capacity);
    }

    public TroveIntHashSet(int[] array) {
        set = new TIntHashSet(array);
    }

    @Override
    public boolean add(Integer e) {
        return set.add(e);
    }

    @Override
    public boolean remove(Object o) {
        return set.remove((Integer) o);
    }

    @Override
    public boolean contains(Object o) {
        return set.contains((Integer) o);
    }

    @Override
    public boolean addAll(Collection<? extends Integer> c) {

        boolean changed = false;
        for (Integer e : c) {
            changed = add(e) || changed;
        }
        return changed;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        int[] array = new int[c.size()];
        int i = 0;
        for (Object o : c) {
            array[i] = (Integer) o;
            i++;
        }
        return set.retainAll(array);
    }

    @Override
    public boolean removeAll(Collection<?> c) {

        boolean changed = false;
        if (c.size() <= set.size()) {
            for (Object o : c) {
                changed = remove(o) || changed;
            }
        } else {
           for (TIntIterator it = set.iterator(); it.hasNext(); ) {
               int e = it.next();
               if (c.contains(e)) {
                   it.remove();
                   changed=true;
               }
           }
        }
        return changed;

//          int[] array = new int[c.size()];
//        int i = 0;
//        for (Object o : c) {
//            array[i] = (Integer) o;
//            i++;
//        }
//        return set.removeAll(array);
    }

    @Override
    public void clear() {
        set.clear();
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public int size() {
        return set.size();
    }

    @Override
    public Iterator<Integer> iterator() {
        return new TroveIntHashSetIterator();
    }

    class TroveIntHashSetIterator implements Iterator<Integer> {

        TIntIterator it;

        public TroveIntHashSetIterator() {
            it = set.iterator();
        }

        @Override
        public boolean hasNext() {
            return it.hasNext();
        }

        @Override
        public Integer next() {
            return it.next();
        }

        @Override
        public void remove() {
            it.remove();

        }
    }
}
